<template>
  <div class="container">
    <!-- 搜索 -->
    <div style="margin: 10px 0;">
      <el-form inline="true">
        <el-form-item>
          <el-button type="primary" @click="showAddForm">新增图书</el-button>
        </el-form-item>
        <el-form-item label="查询类型">
          <el-select v-model="searchType" placeholder="请选择查询类型">
            <el-option label="ISBN" value="isbn"></el-option>
            <el-option label="图书名称" value="bookName"></el-option>
            <el-option label="作者" value="author"></el-option>
            <el-option label="类别" value="category"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="查询目标">
          <el-input v-model="searchTarget" placeholder="请输入查询目标" clearable>
            <template #prefix>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="margin-left: 1%" @click="load" size="small">
            <svg-icon iconClass="search" />
            查询
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="danger" @click="clear">重置</el-button>
        </el-form-item>
        <!-- <el-form-item style="float: right" v-if="numOfOutDataBook != 0">
          <el-popconfirm confirm-button-text="查看" cancel-button-text="取消" :icon="InfoFilled" icon-color="red"
            title="您有图书已逾期，请尽快归还" @confirm="toLook">
            <template #reference>
              <el-button type="warning">逾期通知</el-button>
            </template>
          </el-popconfirm>
        </el-form-item> -->
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData.rows" class="book-table" border>
      <el-table-column fixed prop="bookName" label="书名" />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="category" label="类型" />
      <el-table-column prop="press" label="出版社" />
      <el-table-column prop="isbn" label="ISBN" />
      <el-table-column prop="inventory" label="库存" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="handleDelete(row)">删除</el-button>
          <el-button link type="primary" size="small" @click="handleEdit(row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <!-- <el-pagination layout="prev, pager, next" :total="1000" /> -->
      <el-pagination @current-change="handleCurrentChange" hide-on-single-page :page-size="pageSize" :current-page="currentPage" layout="prev, pager, next" :total="total" />
    </div>

    <!-- 添加表单 -->
    <div class="add-form" v-if="AddFormVisbility">
      <el-form :model="addBookForm" label-width="80px">
        <el-form-item label="ISBN">
          <el-input v-model="addBookForm.isbn"></el-input>
        </el-form-item>
        <el-form-item label="书名">
          <el-input v-model="addBookForm.bookName"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="addBookForm.author"></el-input>
        </el-form-item>
        <el-form-item label="类别">
          <el-input v-model="addBookForm.category"></el-input>
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="addBookForm.press"></el-input>
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="addBookForm.inventory"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
          <el-button @click="AddFormVisbility = false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 修改表单 -->
    <div class="edit-form add-form" v-if="editFormVisible">
      <el-form :model="editForm" label-width="80px">

        <!-- 表单项 -->
        <el-form-item v-for="item in formItems" :key="item.prop" :label="item.label">
          <el-input v-model="editForm[item.prop]" v-if="item.type === 'input'">
          </el-input>

          <el-input-number v-model="editForm[item.prop]" v-else-if="item.type === 'number'">
          </el-input-number>
        </el-form-item>

        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitEditForm">提交</el-button>
          <el-button @click="editFormVisible = false">取消</el-button>
        </el-form-item>

      </el-form>
    </div>
    <div class="overlay" v-if="AddFormVisbility || editFormVisible"></div>
  </div>
</template>

<script setup>
import request from '../utils/request'
import { onMounted, ref, computed } from 'vue';
import { ElMessage } from 'element-plus'

const tableData = ref([]) // 表格数据

// 搜索框
const searchType = ref('')
const searchTarget = ref('')

// 分页
const currentPage = ref('1')
const pageSize = ref(10)
const total = ref(0)

// 控制表单可见性
const AddFormVisbility = ref(false)
const editFormVisible = ref(false)
const addBookForm = ref({
  category: '',
  isbn: '',
  bookName: '',
  author: '',
  press: '',
  inventory: ''
})

// 双向绑定到用户输入 
const editForm = ref({
  isbn: '',
  bookName: '',
  author: '',
  press: '',
  category: '',
  inventory: '',
  id: '',
})
const formItems = [
  { prop: 'isbn', label: 'ISBN', type: 'input' },
  { prop: 'bookName', label: '书名', type: 'input' },
  { prop: 'author', label: '作者', type: 'input' },
  { prop: 'press', label: '出版社', type: 'input' },
  { prop: 'category', label: '类型', type: 'input' },
  { prop: 'inventory', label: '数量', type: 'number' }
]

onMounted(() => {
  fetchData()
})

async function fetchData() {
  try {
    const param = {}
    param[searchType.value] = searchTarget.value
    param.page = currentPage.value
    param.pageSize = pageSize.value
    request.get('/system', {
      params: param
    }).then((res) => {
      tableData.value = res.data
      total.value = res.data.total
    })
  } catch (error) {
    console.log(error)
  }
}

const load = () => {
  console.log(currentPage.value)
  fetchData()
} 

const clear = () => {
  searchType.value = ''
  searchTarget.value = ''
  load()
}

const showAddForm = () => {
  AddFormVisbility.value = true
}

const submitAddForm = () => {
  AddFormVisbility.value = false
  editFormVisible.value = false
  request.post('/system', {
    category: addBookForm.value.category,
    isbn: addBookForm.value.isbn,
    bookName: addBookForm.value.bookName,
    author: addBookForm.value.author,
    press: addBookForm.value.press,
    inventory: addBookForm.value.inventory
  })
    .then((res) => {
      if (res.code === 1) {
        ElMessage({
          message: '添加成功',
          type: 'success',
        })
        load()
      } else {
        ElMessage.error('添加失败')
      }
    })
    .catch((err) => {
      ElMessage.error('网络请求错误')
      console.log(err)
    })
  load()
}

const handleDelete = (row) => {
  const bookToDelete = []
  bookToDelete.push(row.id)
  const url = '/system/' + row.id
  request.delete(url).then((res) => {
    if (res.code === 1) {
      ElMessage({
        message: '删除成功',
        type: 'success',
      })
      load()
    } else {
      ElMessage.error('删除失败')
    }
  }).catch((err) => {
    ElMessage.error('网络请求错误')
    console.log(err)
  })
}

const handleEdit = (row) => {
  editForm.value.isbn = row.isbn
  editForm.value.bookName = row.bookName
  editForm.value.author = row.author
  editForm.value.press = row.press
  editForm.value.category = row.category
  editForm.value.inventory = row.inventory
  editForm.value.id = row.id
  editFormVisible.value = true

}

const submitEditForm = () => {
  editFormVisible.value = false
  request.put('/system', {
    id: editForm.value.id,
    category: editForm.value.category,
    isbn: editForm.value.isbn,
    bookName: editForm.value.bookName,
    author: editForm.value.author,
    press: editForm.value.press,
    inventory: editForm.value.inventory
  })
    .then((res) => {
      if (res.code === 1) {
        ElMessage({
          message: '修改成功',
          type: 'success',
        })
        load()
      } else {
        ElMessage.error('修改失败')
      }
    })
    .catch((err) => {
      ElMessage.error('网络请求错误')
      console.log(err)
    })
  load()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  load()
}

</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  position: relative;
  min-height: 30vh;
  overflow-x: hidden;
  margin-top: 10px;

  .book-table {
    align-self: center;
    width: 80%;
    margin-top: 20px;
    height: 65vh;
  }

  .pagination {
    // justify-items: center;
    align-self: center;
    margin-top: 20px;
  }

  .add-form {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1000; // 浮动在其他内容之上
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  }

  .overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(5px); // 对背景进行模糊处理
    z-index: 999; // 确保覆盖层位于内容之上但在表单之下
  }

}
</style>